<?php

/**
 * 标签关系模型
 *
 * @author 煤老板 <meok23@sina.com>
 * @date   2017-06-07
 */

namespace app\admin\model;

use app\common\logic\Response;
use fw\base\Instance;
use fw\db\DB;
use fw\tool\Request;

class TagRel
{
    use Instance;

    // 所有支持的频道
    private $_channels = ['art'];

    /**
     * 新增一条数据
     *
     * @param array $args
     *
     * @return array
     */
    public function add($args)
    {
        // 参数获取
        $tag = Request::input($args, 'tag', 'trim');
        $obj_id = (int)Request::input($args, 'obj_id');
        $channel = Request::input($args, 'channel', 'trim');

        // 参数校验
        if (empty($tag) || $obj_id < 1 || !in_array($channel, $this->_channels)) {
            return Response::to([400, 'Parameter error.']);
        }

        // 插入数据
        $data = ['tag' => $tag, 'obj_id' => $obj_id, 'channel' => $channel];
        $ret = DB::table('tag_rel')->insert($data);
        if ($ret == false) {
            return Response::log([500, 'Insert fail.', $data], Request::post());
        }

        return Response::to([0, 'Success.']);
    }

    /**
     * 删除关系数据，不一定几条
     *
     * @param array $args
     *
     * @return array
     */
    public function del($args)
    {
        // 参数获取
        $obj_id = (int)Request::input($args, 'obj_id');
        $channel = Request::input($args, 'channel', 'trim');

        // 参数校验
        if ($obj_id < 1 || !in_array($channel, $this->_channels)) {
            return Response::to([400, 'Parameter error.']);
        }

        // 删除记录
        $where = "obj_id=:obj_id AND channel=:channel";
        $prep = [':obj_id' => $obj_id, ':channel' => $channel];
        $affected_rows = DB::table('tag_rel')->where($where, $prep)->delete();
        if ($affected_rows == false) {
            return Response::log([500, 'Delete fail.'], $args);
        }

        return Response::to([0, 'Success.', ['affected_rows' => $affected_rows]]);
    }
}
